//
//  NYRemovedViewController.m
//  Nooryes
//
//  Created by baken on 2020/2/25.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYRemovedViewController.h"
#import "NYRemovedViewModel.h"
#import "NYRemovedCollectionViewController.h"

#import "CHTCollectionViewWaterfallLayout.h"
#import "NYCategoryModel.h"
#import "CustomLabel.h"
#import "NSString+dynamicSize.h"
#import "NYSearchViewController.h"
@interface NYRemovedViewController ()

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UIScrollView *topicScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
@property (weak, nonatomic) IBOutlet UIView *topicView;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topicWidth;

@property (weak, nonatomic) IBOutlet UISearchBar *saerchBar;
@property (nonatomic, strong) NYRemovedViewModel *removedVM;
@end

@implementation NYRemovedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"拔草";
    self.removedVM.type = @"2";
    [self.removedVM getRemovedCategoryWithCompletionHandle:^(NSError *error) {
        if (!error) {
            [self setupTitle];
            [self setChildrenViewController];
            [self scrollViewDidEndScrollingAnimation:self.contentScrollView];
        }
    }];
    
    self.saerchBar.layer.cornerRadius = 14;
    self.saerchBar.layer.masksToBounds = YES;
}


- (void)setChildrenViewController{
    for (int i = 0; i < self.removedVM.topicArray.count; i++) {
        CategoryModel *model = self.removedVM.topicArray[i];
        CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
        NYRemovedCollectionViewController *info = [[NYRemovedCollectionViewController alloc] initWithCollectionViewLayout:layout];
        info.topicID = model.classid;
        
        [self addChildViewController:info];
        
    }
    [self.contentWidth setConstant:self.removedVM.topicArray.count * kScreenWidth];
}



- (void)setupTitle {
    CGFloat totalWidth = 0;
    for (NSInteger i = 0; i < self.removedVM.topicArray.count; i++) {
        CustomLabel *label = [[CustomLabel alloc] init];
        CategoryModel *model = self.removedVM.topicArray[i];
        label.text = model.name;
        
        CGFloat width = [model.name dynamicWidthWithFontSize:15 andCGSize:CGSizeMake(MAXFLOAT, 17) andLineSpace:0].width +20;
        
        CGFloat labelX = totalWidth;
        totalWidth += width;
        label.frame = CGRectMake(labelX, 0, width, 30);
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)]];
        label.tag = i;
        [self.topicView addSubview:label];
        
        if (i == 0) { // 最前面的label
            label.scale = 1.0;
        }
    };
    [self.topicWidth setConstant:totalWidth];
    
}


/**
 * 监听顶部label点击
 */
- (void)labelClick:(UITapGestureRecognizer *)tap
{
    // 取出被点击label的索引
    NSInteger index = tap.view.tag;
    
    UIView *view = self.topicView.subviews[index];
    if ([view isKindOfClass:[CustomLabel class]]) {
        // 让底部的内容scrollView滚动到对应位置
        CGPoint offset = self.contentScrollView.contentOffset;
        offset.x = index * self.contentScrollView.frame.size.width;
        [self.contentScrollView setContentOffset:offset animated:YES];
    }
}


-(void)viewDidLayoutSubviews{
    
}

-(NYRemovedViewModel *)removedVM{
    if (!_removedVM) {
        _removedVM = [NYRemovedViewModel new];
    }
    return _removedVM;
}



#pragma mark UIScrollerView Delegate
/**
 * scrollView结束了滚动动画以后就会调用这个方法（比如- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;方法执行的动画完毕后）
 */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    // 一些临时变量
    CGFloat width = scrollView.frame.size.width;
    CGFloat height = scrollView.frame.size.height;
    CGFloat offsetX = scrollView.contentOffset.x;
    // 当前位置需要显示的控制器的索引
    NSInteger index = offsetX / width;
    
    // 让对应的顶部标题居中显示
    CustomLabel *label = self.topicView.subviews[index];//当前需要显示的label
    
    // 让其他label回到最初的状态
    for (UIView *otherLabel in self.topicView.subviews) {
        if ([otherLabel isKindOfClass:[CustomLabel class]]) {
            if (otherLabel != label) {
                ((CustomLabel *)otherLabel).scale = 0.0;
            }
        }
    }
    
    // 取出需要显示的控制器
    NYRemovedCollectionViewController *willShowVc = self.childViewControllers[index];
    
    // 如果当前位置的位置已经显示过了，就直接返回
    if ([willShowVc isViewLoaded]) {
        //            if (willShowVc.isReload) {
        //                [willShowVc reloadTableView];
        //            }
        return;
    }
    // 添加控制器的view到contentScrollView中;
    willShowVc.view.frame = CGRectMake(offsetX, 0, width, height);
    [scrollView addSubview:willShowVc.view];
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewDidEndScrollingAnimation:scrollView];
}



//scrollView滚动就会调用此方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x < 0) {
        CGPoint offset = self.contentScrollView.contentOffset;
        offset.x = 0;
        [self.contentScrollView setContentOffset:offset animated:NO];
    }else {
        CGFloat scale = scrollView.contentOffset.x / scrollView.frame.size.width;
        if (scale < 0 || scale > self.topicView.subviews.count - 1) {
            return;
        }
        NSInteger leftIndex = scale; //当前滚动的label的索引（整数）];
        CustomLabel *leftLabel = self.topicView.subviews[leftIndex];
        
        NSInteger rightIndex = leftIndex + 1;
        CustomLabel *rightLabel = (rightIndex == self.removedVM.topicArray.count) ? nil : self.topicView.subviews[rightIndex];
        // 右边比例
        CGFloat rightScale = scale - leftIndex;
        // 左边比例
        CGFloat leftScale = 1 - rightScale;
        
        // 设置label的比例
        leftLabel.scale = leftScale;
        rightLabel.scale = rightScale;
        
        
        CGPoint titleOffset = self.topicScrollView.contentOffset;
        titleOffset.x = leftLabel.center.x - scrollView.frame.size.width * 0.5;
        CGFloat maxTitleOffsetX = self.topicScrollView.contentSize.width - scrollView.frame.size.width;
        // 左边超出处理
        if (titleOffset.x < 0) {
            titleOffset.x = 0;
        } else if (titleOffset.x > maxTitleOffsetX){// 右边超出处理
            titleOffset.x = maxTitleOffsetX;
            if (self.topicScrollView.contentSize.width < kScreenWidth) {
                titleOffset.x = 0;
            }
        }
        
        [self.topicScrollView setContentOffset:titleOffset animated:YES];
    }
}


#pragma mark UISearchBar Delegate

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    NYSearchViewController *searchViewController = [[NYSearchViewController alloc] initWithNibName:@"NYSearchViewController" bundle:nil];
    [self.navigationController pushViewController:searchViewController animated:YES];
    
    return NO;
}

@end
